<?php
/**
 * Created by PhpStorm.
 * User: huyi
 * Date: 2018/1/26
 * Time: 16:50
 */
require_once __DIR__ . './../vendor/autoload.php';use PhpAmqpLib\Connection\AMQPStreamConnection;

$exchange_name = 'direct_logs';
$connection    = new AMQPStreamConnection('localhost', 5672, 'huyi', 'huyi123');
$channel       = $connection->channel();

$channel->exchange_declare($exchange_name, 'direct', false, false, false);

list($queue_name, ,) = $channel->queue_declare("", false, false, true, false);

$severities = array_slice($argv, 1);
if(empty($severities)){
    file_put_contents('php://stderr', "Usage: $argv[0] [info] [warning] [error]\n");
    exit(1);
}

foreach($severities as $severity){
    $channel->queue_bind($queue_name, 'direct_logs', $severity);
}

echo ' [*] Waiting for logs. To exit press CTRL+C', "\n";

$callback = function ($msg){
    echo ' [x] ', $msg->delivery_info['routing_key'], ':', $msg->body, "\n";
};

$channel->basic_consume($queue_name, '', false, true, false, false, $callback);

while(count($channel->callbacks)){
    $channel->wait();
}

$channel->close();
$connection->close();

/**
 * 如果你只想将 warning 和 error (而非 info) 日志信息保存到文件中，只用打开一个控制台键入:
 * php receive_logs_direct.php warning error > logs_from_rabbit.log
 * 1
 * 如果你想在屏幕上看到所有的日志信息，打开一个控制台键入：
 * php receive_logs_direct.php info warning error
 * 1
 * 而且，例如，要发送 error 类型日志，只需要键入：
 * php emit_log_direct.php error "Run. Run. Or it will explode."
 */